<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否完工" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择是否完工" clearable>
          <el-option
            v-for="dict in dict.type.doc_project_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="项目经理名称" prop="xmjlName">
        <el-input
          v-model="queryParams.xmjlName"
          placeholder="请输入项目经理名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['documents:project:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['documents:project:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['documents:project:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['documents:project:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="documentsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="项目编号" align="center" prop="id" />
      <el-table-column label="项目名称" align="center" prop="name" />
      <el-table-column label="是否完工" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.doc_project_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="项目经理名称" align="center" prop="xmjlName" />
      <el-table-column label="合同" align="center" prop="xmjlName">
        <el-button type="text" @click="handleOpenFile(1)">点击查看</el-button>
      </el-table-column>
      <el-table-column label="竣工报告" align="center" prop="xmjlName">
        <el-button type="text" @click="handleOpenFile(2)">点击查看</el-button>
      </el-table-column>>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['documents:project:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['documents:project:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改项目信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="是否完工" prop="status">
          <el-select v-model="form.status" placeholder="请选择是否完工">
            <el-option
              v-for="dict in dict.type.doc_project_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目经理" prop="xmjlName">
          <el-select
            @change="handleChangeXmjl"
            placeholder="请输入项目经理编号或姓名"
            v-model="value" filterable
            :filter-method="filterMethod">
            <el-option
              v-for="(item,i) in listXmjl2"
              :key="item.i"
              :label="item.xmjlName"
              :value="item.xmjlId"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="合同文件">
          <el-upload
            action="#"
            :file-list="fileList1"
            :show-file-list="false"
            :http-request="httpRequest"
            :before-upload="beforeUpload"
            :before-remove="beforeRemove"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          <el-table :data="tableFile1">
            <el-table-column label="名称" prop="originalFileName" />
            <el-table-column label="操作" prop="originalFileName">
              <template slot-scope="scope">
                <el-button type="text" @click="downloadFile(scope.row.url,scope.row.originalFileName)">下载</el-button>
                <el-button type="text" @click="handleDeleteFile(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParamsFile1.pageNum"
            :limit.sync="queryParamsFile1.pageSize"
            @pagination="_listContract"
          />
        </el-form-item>

        <el-form-item label="竣工报告">
          <el-upload
            action="#"
            :file-list="fileList2"
            :show-file-list="false"
            :http-request="httpRequest"
            :before-upload="beforeUpload2"
            :before-remove="beforeRemove"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          <el-table :data="tableFile2">
            <el-table-column label="名称" prop="originalFileName" />
            <el-table-column label="操作" prop="originalFileName">
              <template slot-scope="scope">
                <el-button type="text" @click="downloadFile(scope.row.url,scope.row.originalFileName)">下载</el-button>
                <el-button type="text" @click="handleDeleteFile2(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParamsFile1.pageNum"
            :limit.sync="queryParamsFile1.pageSize"
            @pagination="_listContract"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 文件 -->
    <el-dialog :title="titleFile" :visible.sync="openFile" width="500px" append-to-body>
      <div v-if="titleFile == '查看合同文件'">
        <el-table :data="tableFile1">
          <el-table-column label="名称" prop="originalFileName" />
          <el-table-column label="操作" prop="originalFileName">
            <template slot-scope="scope">
              <el-button type="text" @click="downloadFile(scope.row.url,scope.row.originalFileName)">下载</el-button>
              <el-button type="text" @click="handleDeleteFile(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="file1Total>0"
          :total="file1Total"
          :page.sync="queryParamsFile1.pageNum"
          :limit.sync="queryParamsFile1.pageSize"
          @pagination="_listContract"
        />
      </div>

      <div v-else>
        <el-table :data="tableFile2">
          <el-table-column label="名称" prop="originalFileName" />
          <el-table-column label="操作" prop="originalFileName">
            <template slot-scope="scope">
              <el-button type="text" @click="downloadFile(scope.row.url,scope.row.originalFileName)">下载</el-button>
              <el-button type="text" @click="handleDeleteFile(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="file2Total>0"
          :total="file2Total"
          :page.sync="queryParamsFile2.pageNum"
          :limit.sync="queryParamsFile2.pageSize"
          @pagination="_listCompletion"
        />
      </div>

    </el-dialog>
  </div>
</template>

<script>
import {
  listDocuments,
  getDocuments,
  delDocuments,
  addDocuments,
  updateDocuments
} from "@/api/xz/documents/project";
import {listAllXmjl} from "@/api/xz/documents/xmjl";
import {addContract, delContract, getContract, listAllContract, listContract} from "@/api/xz/documents/contract";
import {addCompletion, delCompletion, listCompletion} from "@/api/xz/documents/completion";
export default {
  name: "Documents",
  dicts: ['doc_project_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中数组项目经理id
      xmjlids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目信息表格数据
      documentsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        status: null,
        xmjlName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "项目名称不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "是否完工不能为空", trigger: "change" }
        ],
      },
      fileList1: [], // 合同文件
      fileList2: [], // 竣工报告
      listXmjl1: [], // 存储原始数据
      listXmjl2: [],
      value: "",
      projectId: null, // 选中的项目id
      tableFile1: [], // 回显合同图片
      file1Total: 0,
      queryParamsFile1: {
        pageNum: 1,
        pageSize: 10,
      },
      tableFile2: [], // 回显竣工报告
      file2Total: 0,
      queryParamsFile2: {
        pageNum: 1,
        pageSize: 10,
      },
      titleFile: "",
      openFile: false,
    };
  },
  created() {
    this.getList();
    this._listAllXmjl();
  },
  methods: {
    /** 查询项目信息列表 */
    getList() {
      this.loading = true;
      listDocuments(this.queryParams).then(response => {
        this.documentsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询全部为完工项目人员信息 */
    _listAllXmjl() {
      return listAllXmjl(
        {
          status: 0,
        }
      ).then((res)=>{
        this.listXmjl1 = res.data;
        this.listXmjl2 = [...res.data];
      });
    },
    filterMethod(query) {
      console.log("query",query)
      this.listXmjl2 = [];
      this.listXmjl2 = this.listXmjl1.filter((xmjl)=>{
        return xmjl.xmjlId.includes(query) || xmjl.xmjlName.includes(query);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        status: null,
        delFlag: null,
        userId: null,
        deptId: null,
        xmjlId: null,
        xmjlName: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.value = null;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.xmjlids = selection.map(item => item.xmjlId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加项目信息";
    },
    _listContract() {
      listContract({
        projectId: this.projectId,
      }).then(response => {
        this.tableFile1 = response.rows;
      });
    },
    _listCompletion() {
      listCompletion({
        projectId: this.projectId,
      }).then(response => {
        this.tableFile2 = response.rows;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      this.listXmjl1 = [];
      this.listXmjl2 = [];
      this.projectId = row.id;
      this._listContract();
      getDocuments(id).then(response => {
        console.log(response)
        this.form = response.data;
        this.form.oldXmjlId = response.data.xmjlId;
        this.value = this.form.xmjlId;
        this.open = true;
        this.title = "修改项目信息";
        this._listAllXmjl().then(res=>{
          console.log(123)
          this.listXmjl1.push({
            xmjlName: this.form.xmjlName,
            xmjlId: this.form.xmjlId,
          });
          this.listXmjl2.push({
            xmjlName: this.form.xmjlName,
            xmjlId: this.form.xmjlId,
          });
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDocuments(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this._listAllXmjl();
              this.getList();
            });
          } else {
            console.log(this.form)
            addDocuments(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this._listAllXmjl();
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const xmjlids = row.xmjlId || this.xmjlids;
      this.$modal.confirm('是否确认删除项目信息编号为"' + ids + '"的数据项？').then(function() {
        return delDocuments(ids,xmjlids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('documents/documents/export', {
        ...this.queryParams
      }, `documents_${new Date().getTime()}.xlsx`)
    },
    async beforeUpload(file) {
      const formData = new FormData();
      formData.append("file",file);
      const res = await this.$upload(formData);
      await addContract({
        projectId: this.projectId,
        originalFileName: res.originalFilename,
        newFileName: res.newFileName,
        url: res.fileName,
      });
      this._listContract();
      this.$modal.msgSuccess("图片上传成功");
      // return this.$upload(formData).then((res)=>{
      //   // 上传图片后 回显
      //   console.log(res)
      //   return addContract(
      //     {
      //       projectId: this.projectId,
      //       originalFilename: res.originalFilename,
      //       newFileName: res.newFileName,
      //       url: res.fileName,
      //     }
      //   ).then((resC)=>{
      //     console.log("resC",resC)
      //     console.log("then")
      //     file.id = resC.data.id;
      //     return Promise.resolve();
      //   });
      // }).then(()=>{
      //   console.log("ok")
      //   return Promise.resolve();
      // }).catch(()=>{
      //   console.log("uploadcatch")
      //   return Promise.reject();
      // });
    },

    async beforeUpload2(file) {
      const formData = new FormData();
      formData.append("file",file);
      const res = await this.$upload(formData);
      await addCompletion({
        projectId: this.projectId,
        originalFileName: res.originalFilename,
        newFileName: res.newFileName,
        url: res.fileName,
      });
      this._listCompletion();
      this.$modal.msgSuccess("图片上传成功");
      // return this.$upload(formData).then((res)=>{
      //   // 上传图片后 回显
      //   console.log(res)
      //   return addContract(
      //     {
      //       projectId: this.projectId,
      //       originalFilename: res.originalFilename,
      //       newFileName: res.newFileName,
      //       url: res.fileName,
      //     }
      //   ).then((resC)=>{
      //     console.log("resC",resC)
      //     console.log("then")
      //     file.id = resC.data.id;
      //     return Promise.resolve();
      //   });
      // }).then(()=>{
      //   console.log("ok")
      //   return Promise.resolve();
      // }).catch(()=>{
      //   console.log("uploadcatch")
      //   return Promise.reject();
      // });
    },

    beforeRemove(file, fileList) {

    },
    // 文件上传
    httpRequest(file) {

    },
    // 选择项目经理
    handleChangeXmjl(id) {
      const xmjl = this.listXmjl2.find(v=>v.xmjlId = id);
      this.form.xmjlId = xmjl.xmjlId;
      this.form.xmjlName = xmjl.xmjlName;
    },
    // 下载文件
    downloadFile(url,fileName) {
      this.$download.resource(url);
      console.log(this.$download)
    },
    // 删除文件
    handleDeleteFile(id) {
      this.$modal.confirm('是否确认删除？').then(function() {
        return delContract(id);
      }).then(() => {
        this._listContract();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    // 删除文件
    handleDeleteFile2(id) {
      this.$modal.confirm('是否确认删除？').then(function() {
        return delCompletion(id);
      }).then(() => {
        this._listCompletion();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 查看文件
    handleOpenFile(i) {
      if (i == 1) {
        this.titleFile = "查看合同文件";
        this.openFile = true;
        this._listContract();
      }else if(i == 2) {
        this.titleFile = "查看竣工合同文件";
        this.openFile = true;
        this._listCompletion();
      }
    },
  }
};
</script>
